package com.example.reservationbilliards.service;

import com.alibaba.fastjson2.JSON;
import com.example.reservationbilliards.pojo.*;
import com.example.reservationbilliards.task.TokenCacheTasks;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReservationService {

    @Autowired
    private TokenCacheTasks tokenCacheService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private CourseStrategy courseStrategy;
    @Value("${retry.config.retryCount}")
    private int retryCount;
    @Value("${retry.config.intervalTime}")
    private int intervalTime;

    @Async("taskExecutor") // 使用配置的线程池
    public CompletableFuture<Void> reserveAsync(UserConfig userConfig) {
        String token = tokenCacheService.getToken(userConfig.getMobile());
        if (token == null) {
            System.out.println("找不到用户令牌: " + userConfig.getMobile());
            return CompletableFuture.completedFuture(null);
        }

        // 1. 获取课程列表
        List<CourseListResponse.Course>  courses = getAvailableCourses(userConfig, token);

        //按策略筛选课程id
        List<Integer> courseIds = courses.stream().filter(course ->
                // 原有条件：可预约状态 + 剩余名额 > 0
                "10".equals(course.getCourseButtonStatus().getCode()) && course.getRemainNumber() > 0 &&
                        // 新增条件：匹配课程名称和时间段
                        userConfig.getCourse().getTargetCourseName().equals(course.getCourseName()) && userConfig.getCourse().getTargetTimeRanges().contains(course.getTimeDetail())).sorted((c1, c2) -> {
            // 策略优先级：按时间段的顺序（11:00-13:00 优先）
            int index1 = userConfig.getCourse().getTargetTimeRanges().indexOf(c1.getTimeDetail());
            int index2 = userConfig.getCourse().getTargetTimeRanges().indexOf(c2.getTimeDetail());
            return Integer.compare(index1, index2);
        }).map(CourseListResponse.Course::getCourseClassArrangeId).collect(Collectors.toList());
        log.info("可用符合策略课程id:{}",courseIds);

        if (courseIds.isEmpty()) {
            System.out.println("用户没有可用的课程: " + userConfig.getMobile());
            return CompletableFuture.completedFuture(null);
        }
        // 2.按优先级尝试预约（先尝试11:00-13:00，再17:00-20:00）
        for (int courseId : courseIds) {
            if (reserveWithCourseId(userConfig, token, courseId)) {
                log.info("预约课程 " + courseId + " 用户: " + userConfig.getMobile());
//                break; // 成功则终止尝试
            }
        }
        return CompletableFuture.completedFuture(null);
    }

    private boolean reserve(UserConfig userConfig, String token, int courseId) {
        String reserveUrl = "https://opapp.grandjoy.com/api/course/reservation/" + courseId + "?projectId=1&userId=" + userConfig.getUserId();

        ReservationRequest reservationRequest = new ReservationRequest();
        reservationRequest.setAppVersion("1.1.12");
        reservationRequest.setDeviceNum(UUID.randomUUID().toString());
        reservationRequest.setImsi(null);
        reservationRequest.setDeviceType("20");
        reservationRequest.setSkinClass("dark-theme");
        reservationRequest.setOriginType("10");
        reservationRequest.setVersion("1.0");
        reservationRequest.setTimestamp(System.currentTimeMillis());
        reservationRequest.setToken(token);
        reservationRequest.setProjectId(userConfig.getProjectId());

        // 替换课程ID
        ReservationRequest.ReservationData reservationData = new ReservationRequest.ReservationData();
        reservationData.setCourseClassArrangeId(courseId); // 动态设置课程ID
        reservationRequest.setData(reservationData);


        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<ReservationRequest> requestEntity = new HttpEntity<>(reservationRequest, headers);
        log.info("预约人：{}，预约课程id：{}",userConfig.getUserId(),courseId);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(reserveUrl, requestEntity, String.class);
        log.info("响应结果：{}", responseEntity.getBody());
        return responseEntity.getStatusCode() == HttpStatus.OK;
    }

    //重试机制
    private List<CourseListResponse.Course>  reserveWithRetry(UserConfig userConfig, String token, int retryCount) {
        for (int i = 0; i < retryCount; i++) {
            log.info("课程列表重试获取第{}次。", i + 1);
            List<CourseListResponse.Course>  availableCourses = getCourseList(userConfig, token);
            if (!availableCourses.isEmpty()) {
                return availableCourses;
            }
            try {
                Thread.sleep(intervalTime); // 重试间隔1秒
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        return Collections.emptyList();
    }

    // 获取可预约课程列表
    private List<CourseListResponse.Course>  getAvailableCourses(UserConfig userConfig, String token) {
        List<CourseListResponse.Course> courseList = getCourseList(userConfig, token);
        //如果没有获取到列表，则重试几次
        if (courseList.isEmpty()){
            List<CourseListResponse.Course>  courses = reserveWithRetry(userConfig, token, retryCount);
            if(!Objects.requireNonNull(courses).isEmpty()){
                log.info("获取成功!");
                return courses;
            }
        }
        return courseList;

    }

    //获取课程列表
    private List<CourseListResponse.Course>  getCourseList(UserConfig userConfig, String token) {
        String courseListUrl = "https://opapp.grandjoy.com/api/course/getCourseList?projectId=1&userId=" + userConfig.getUserId();

        CourseListRequest request = new CourseListRequest();
        request.setAppVersion("1.1.12");
        request.setDeviceNum(UUID.randomUUID().toString());
        request.setImsi(null);
        request.setDeviceType("20");
        request.setSkinClass("dark-theme");
        request.setOriginType("10");
        request.setVersion("1.0");
        request.setTimestamp(System.currentTimeMillis());
        request.setToken(token);
        request.setProjectId(1);

        CourseListRequest.CourseListData data = new CourseListRequest.CourseListData();
        data.setStartTime(LocalDate.now().toString()); // 当天日期
        request.setData(data);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<CourseListRequest> requestEntity = new HttpEntity<>(request, headers);

        try {
            ResponseEntity<CourseListResponse> response = restTemplate.postForEntity(courseListUrl, requestEntity, CourseListResponse.class);
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                if ("1".equals(response.getBody().getCode()) && !response.getBody().getResult().isEmpty()) {
                    log.info("获取课程列表成功");
                    log.info("课程列表：" + JSON.toJSONString(response.getBody().getResult()));
                    return response.getBody().getResult();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("Failed to get courses for user: " + userConfig.getMobile());
        }
        log.info("获取课程列表失败");
        return Collections.emptyList();
    }
    // 使用课程ID进行预约
    private boolean reserveWithCourseId(UserConfig userConfig, String token, int courseId) {
        // ... 发送请求逻辑（保持原有代码）
        return reserve(userConfig, token, courseId);
    }

}